package com.example.service;

import com.example.config.FileUploadConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
public class FileService {
    @Autowired
    private FileUploadConfig fileUploadConfig;

    public String uploadFile(MultipartFile file, String directory) {
        try {
            // 检查文件大小
            if (file.getSize() > fileUploadConfig.getMaxSize()) {
                throw new RuntimeException("文件大小超过限制");
            }

            // 检查文件类型
            String fileType = StringUtils.getFilenameExtension(file.getOriginalFilename());
            if (!fileUploadConfig.getAllowedTypes().contains(fileType.toLowerCase())) {
                throw new RuntimeException("不支持的文件类型");
            }

            // 生成新的文件名
            String fileName = UUID.randomUUID().toString() + "." + fileType;
            
            // 创建目录
            Path uploadPath = Paths.get(fileUploadConfig.getPath(), directory);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 保存文件
            Path filePath = uploadPath.resolve(fileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 返回文件访问路径
            return directory + "/" + fileName;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }
} 